<template>
  <div class="company-settings-info-view" :style="{ minHeight: `${layoutContentHeight - pageHeaderHeight - 24}px` }">
    <a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit">
      <a-form-item :label="$t('platformManagement.company.companyCode')">
        <s-input
          :disabled="!canEdit"
          v-decorator="[
            'code',
            {
              rules: [
                {
                  required: true,
                  message: this.$t('common.emptyErr', {
                    name: this.$t('platformManagement.company.companyCode')
                  })
                },
                { pattern: /^[\d\w]{1,32}$/, message: '请输入正确的企业编码' }
              ]
            }
          ]"
          :limit="32"
        />
      </a-form-item>

      <a-form-item :label="$t('platformManagement.app.visitUrl')">
        <a-textarea
          :disabled="!canEdit"
          :autoSize="{ minRows: 1, maxRows: 3 }"
          placeholder="http://abc.com or https://abc.com"
          v-decorator="[
            'url',
            {
              rules: [
                { required: true, message: '请输入网站地址', transform: val => val && val.trim() },
                { pattern: isBasicUrl, message: '请输入正确的网站地址' },
                { validator: validateUrl }
              ]
            }
          ]"
        />
      </a-form-item>

      <a-form-item
        :label="$t('platformManagement.app.enterpriseLogo')"
        :extra="
          $t('platformManagement.app.recommendImg', {
            resolution: `${logoPixel.width}*${logoPixel.height}`,
            size: '5M',
            format: 'jpg、png'
          })
        "
      >
        <a-input
          v-show="false"
          v-decorator="[
            'logoPic',
            {
              rules: [{ required: true, message: '请上传企业LOGO' }]
            }
          ]"
        />
        <a-upload
          :disabled="!canEdit"
          name="file"
          listType="picture-card"
          class="logo-uploader"
          :showUploadList="false"
          accept="image/jpeg,image/png"
          :before-upload="beforeUpload"
          :customRequest="customRequest"
          @change="info => handleChange(info, 'logoPic')"
        >
          <img v-if="logoPic && !logoPicUploading" :src="logoPic | imgURLFilter" alt="logo" />
          <div v-else>
            <a-icon :type="logoPicUploading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-item>

      <a-form-item
        :label="$t('platformManagement.app.thumbnail')"
        :extra="
          $t('platformManagement.app.recommendImg', {
            resolution: `${iconPixel.width}*${iconPixel.height}`,
            size: '5M',
            format: 'jpg、png'
          })
        "
      >
        <a-input
          v-show="false"
          v-decorator="[
            'iconPic',
            {
              rules: [{ required: true, message: $t('platformManagement.app.uploadAppLogo') }]
            }
          ]"
        />
        <a-upload
          :disabled="!canEdit"
          name="file"
          listType="picture-card"
          class="icon-uploader"
          :showUploadList="false"
          accept="image/jpeg,image/png"
          :before-upload="beforeUpload"
          :customRequest="customRequest"
          @change="info => handleChange(info, 'iconPic')"
        >
          <img v-if="iconPic && !iconPicUploading" :src="iconPic | imgURLFilter" alt="icon" />
          <div v-else>
            <a-icon :type="iconPicUploading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">{{ $t('common.upload') }}</div>
          </div>
        </a-upload>
      </a-form-item>

      <a-form-item
        :label="$t('platformManagement.app.loginBgi')"
        :extra="
          $t('platformManagement.app.recommendImg', {
            resolution: `${loginPixel.width}*${loginPixel.height}`,
            size: '5M',
            format: 'jpg、png'
          })
        "
      >
        <a-input
          v-show="false"
          v-decorator="[
            'loginPic',
            {
              rules: [{ required: true, message: $t('platformManagement.app.uploadLoginBgi') }]
            }
          ]"
        />
        <a-upload
          :disabled="!canEdit"
          name="file"
          listType="picture-card"
          class="login-uploader"
          :showUploadList="false"
          accept="image/jpeg,image/png"
          :before-upload="beforeUpload"
          :customRequest="customRequest"
          @change="info => handleChange(info, 'loginPic')"
        >
          <img v-if="loginPic && !loginPicUploading" :src="loginPic | imgURLFilter" alt="login" />
          <div v-else>
            <a-icon :type="loginPicUploading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">{{ $t('common.upload') }}</div>
          </div>
        </a-upload>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 4 }">
        <a-button v-action:update @click="getBaseInfo">{{ $t('common.cancel') }}</a-button>
        <a-button
          v-action:update
          type="primary"
          style="margin-left: 8px;"
          html-type="submit"
          :loading="confirmLoading"
          >{{ $t('common.update') }}</a-button
        >
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { uploadFile } from '@/api/common';
import { updateBaseInfo } from '@/api/company';
import { isBasicUrl } from '@/utils/regExp';
import { layoutMixin } from '@/utils/mixin';
import { SInput } from '@/components';

export default {
  name: 'BaseSetting',
  mixins: [layoutMixin],
  components: {
    SInput
  },
  data() {
    return {
      isBasicUrl,
      form: this.$form.createForm(this),
      confirmLoading: false,
      logoPic: '',
      logoPicUploading: false,
      iconPic: '',
      iconPicUploading: false,
      loginPic: '',
      loginPicUploading: false,
      loginPixel: {
        width: 504,
        height: 408
      },
      logoPixel: {
        width: 208,
        height: 64
      },
      iconPixel: {
        width: 64,
        height: 64
      },
      canEdit: this.$auth('update', this.$route.meta.permissionId)
    };
  },
  mounted() {
    this.getBaseInfo();
  },
  methods: {
    // 获取基础信息
    getBaseInfo() {
      const { iconPic, logoPic, loginPic, url, code } = this.$store.state.user;
      this.form.setFieldsValue({
        code,
        url,
        iconPic,
        logoPic,
        loginPic
      });
      this.iconPic = iconPic;
      this.logoPic = logoPic;
      this.loginPic = loginPic;
    },
    // 域名校验
    validateUrl(rule, value, callback) {
      if ((value && value.indexOf('127.0.0.1') > -1) || value.indexOf('localhost') > -1) {
        callback('请输入正确的地址');
      } else {
        callback();
      }
    },
    // 文件大小校验
    beforeUpload(file) {
      const isLtSize = file.size / 1024 / 1024 < 5;
      if (!isLtSize) {
        this.$message.error('图片大小不能超过 5MB!');
      }
      return isLtSize;
    },
    // 上传变化
    handleChange(info, type) {
      const { status } = info.file;
      if (status === 'uploading') {
        this[`${type}Uploading`] = true;
      } else if (status === 'done') {
        const { response } = info.file;
        this[type] = response.data;
        this[`${type}Uploading`] = false;
        this.form.setFieldsValue({
          [type]: response.data
        });
      } else if (status === 'error') {
        this[`${type}Uploading`] = false;
      }
    },
    // 上传文件
    async customRequest({ file, filename, onSuccess, onError }) {
      const formData = new FormData();
      formData.append(filename, file);
      const res = await uploadFile(formData);
      if (res.code === 'sso.ok') {
        onSuccess(res);
      } else {
        onError();
      }
    },
    // 更新信息
    handleSubmit(e) {
      e.preventDefault();
      const {
        form: { validateFields, getFieldsValue }
      } = this;
      this.confirmLoading = true;
      validateFields((errors, values) => {
        if (!errors) {
          const req = { ...values };
          for (let key in req) {
            if (['url', 'code'].includes(key)) {
              req[key] = req[key] ? req[key].trim() : '';
            }
          }
          updateBaseInfo(req)
            .then(res => {
              if (res.code === 'sso.ok') {
                this.$message.success(res.message);
                this.$store.dispatch('setLoginConfig', req);
              }
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        } else {
          this.confirmLoading = false;
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.input {
  max-width: 500px;
}
.cover-wrap {
  width: 500px;
}
.logo-uploader {
  /deep/ .ant-upload-select-picture-card {
    width: 208px;
    height: 64px;
  }
  img {
    max-width: 208px;
    max-height: 64px;
  }
}
.login-uploader {
  /deep/ .ant-upload-select-picture-card {
    width: 378px;
    height: 306px;
  }
  img {
    max-width: 378px;
    max-height: 306px;
  }
}
.icon-uploader {
  /deep/ .ant-upload-select-picture-card {
    width: 64px;
    height: 64px;
  }
  img {
    max-width: 64px;
    max-height: 64px;
  }
}
</style>
